package ec.atreasure.com.core.download;

import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;

import com.blankj.utilcode.util.StringUtils;

import java.io.File;
import java.io.InputStream;

import ec.atreasure.com.core.app.Atreasure;
import ec.atreasure.com.core.net.callback.IRequest;
import ec.atreasure.com.core.net.callback.ISuccess;
import ec.atreasure.com.core.utils.file.FileUtil;
import okhttp3.ResponseBody;

/**
 * Description : 异步下载文件
 * Created by wangjin on 2019/6/24.
 * Job number：
 * Phone ：18301070822
 * Email： 120182051@qq.com
 * Person in charge : 汪渝栋
 * Leader：
 */
public final class SaveFileTask extends AsyncTask<Object, Void, File> {

    private final IRequest requestCallback;
    private final ISuccess successCallback;

    SaveFileTask(IRequest requestCallback, ISuccess successCallback) {
        this.requestCallback = requestCallback;
        this.successCallback = successCallback;
    }

    @Override
    protected File doInBackground(Object... objects) {
        String downloadDir = (String) objects[0];
        String extension = (String) objects[1];
        final ResponseBody body = (ResponseBody) objects[2];
        final String fileName = (String) objects[3];
        final InputStream is = body.byteStream();

        if (StringUtils.isEmpty(downloadDir)) {
            downloadDir = "atreasure_download";
        }

        if (StringUtils.isEmpty(extension)) {
            extension = "";
        }

        if (StringUtils.isEmpty(fileName)) {
            return FileUtil.writeToDisk(is, downloadDir, extension.toUpperCase(), extension);
        } else {
            return FileUtil.writeToDisk(is, downloadDir, fileName);
        }
    }

    @Override
    protected void onPostExecute(File file) {
        super.onPostExecute(file);
        if (successCallback != null) {
            successCallback.onSuccess(file.getPath());
        }
        if (requestCallback != null) {
            requestCallback.onEndRequest();
        }

        autoInstallApk(file);
    }

    /**
     * 安装apk
     * @param file
     */
    private void autoInstallApk(File file) {
        if (FileUtil.getExtension(file.getPath()).equals("apk")) {
            final Intent install = new Intent();
            install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            install.setAction(Intent.ACTION_VIEW);
            install.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            Atreasure.getApplicationContext().startActivity(install);
        }
    }
}
